import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import dayjs from 'dayjs'

/** @description 请求响应参数(不包含data) */
// interface Result {
//   /** 请求码 */
//   code: string
//   /** 请求信息 */
//   msg: string
// }

/** @description 请求响应参数(包含data) */
// interface ResultData<T = unknown> extends Result {
//   data: T
// }
/* 本地JSON请求 */
class LocaleHttp {
  private service: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config)

    /* 请求拦截器 */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        config.url += `?temp=${dayjs().valueOf()}`
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      },
    )

    /* 响应拦截器 */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        return response.data
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      },
    )
  }

  Get<T = unknown>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {
    return this.service.get(url, { params, ...config })
  }
}

const local = {
  baseURL: `${location.origin}`,
  timeout: 1000 * 600,
} as const

const localeHttp = new LocaleHttp(local)

export { localeHttp }
